package jdbmaplite.connection.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import jdbmaplite.connection.DBConnectionFactory;

import com.mchange.v2.c3p0.DataSources;

public class JNDIConnectionFactory extends DBConnectionFactory {

	private DataSource connectionPool = null;

	/**
	 * Default constructor.
	 * 
	 * @param url
	 *            String
	 * @throws NamingException
	 */
	public JNDIConnectionFactory(String url) throws NamingException {
		super("", url, "", "");
	}

	public void loadProperties(Properties properties) throws SQLException {
		properties.remove("driver");
		properties.remove("url");
		properties.remove("user");
		properties.remove("password");
		InitialContext ictx;
		try {
			ictx = new InitialContext(properties);
			connectionPool = (DataSource) ictx.lookup(getUrl());
		} catch (NamingException e) {
			throw new SQLException(e.getMessage());
		}
	}

	public Connection getConnection() throws SQLException {
		return connectionPool.getConnection();
	}

	public void destroy() throws SQLException {
		DataSources.destroy(connectionPool);
	}

	/**
	 * Get ConnectionPool
	 * 
	 * @return DataSource
	 */
	public DataSource getConnectionPool() {
		return connectionPool;
	}

	/**
	 * Set ConnectionPool
	 * 
	 * @param connectionPool
	 *            DataSource
	 */
	public void setConnectionPool(DataSource connectionPool) {
		this.connectionPool = connectionPool;
	}

}